/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.backing;

import com.ez2find.manager.ForumManagerLocal;
import com.ez2find.manager.MessageManagerLocal;
import com.ez2find.manager.NickManagerLocal;
import com.ez2find.manager.SearchLocal;
import com.ez2find.manager.TopicManagerLocal;
import com.ez2find.model.Forum;
import com.ez2find.model.Topic;
import com.ez2find.model.Message;
import com.ez2find.util.SessionContext;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import com.ez2find.model.Nick;
import com.ez2find.services.EmailLocal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.internet.InternetAddress;

/**
 *
 * @author org.@le
 */
public class ForumsSession {

    private Forum currentForum;
    private Topic currentThread;
    private int treeForum;
    private Message currentMessage;
    private Message currentReply;
    private Long nickId;
    private Boolean created;
    private Boolean last;
    private String handleSearchString;
    private String searchString;
    private List<Message> messagesFound;
    private List<Topic> threadsFound;
    private Nick handleFound;
    private String email;
    private String from;
    private int aux1;
    private int aux2;
    @EJB
    MessageManagerLocal ejbMessages;
    @EJB
    TopicManagerLocal ejbTopics;
    @EJB
    ForumManagerLocal ejbForums;
    @EJB
    SearchLocal ejbSearch;
    @EJB
    NickManagerLocal ejbHandles;
    @EJB
    EmailLocal ejbEmail;

    /** Creates a new instance of ForumsSession */
    public ForumsSession() {
    }

    public String sendEmail() throws UnsupportedEncodingException {
        InternetAddress desde = new InternetAddress();
        InternetAddress para = new InternetAddress();

        desde.setAddress(from);
        para.setAddress(email);

        try {
            System.out.println("DESDE: " + from);
            System.out.println("PARA: " + email);
            para.validate();

            if (!from.isEmpty()) {
                desde.validate();
            }
        } catch (Exception e) {
            FacesMessage msg = new FacesMessage("Invalid email address(es).");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
        String s = currentMessage.getSubject();
        String m = currentMessage.getContent();
        System.out.println("1Sending email... ");
        if (ejbEmail.sendPost(from, email, s, m)) {
            FacesMessage msg = new FacesMessage("Email sent correctly.");
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "emailSent";
        } else {
            FacesMessage msg = new FacesMessage("Invalid email address(es).");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

    public List<Topic> getTotalTopics() {
        List<Topic> topics = ejbTopics.invertedTopics(currentForum);
        if (getLast() != null && getLast() != false) {
            Date fechaActual = new Date();
            List<Topic> lastTopics = new ArrayList<Topic>();
            for (Topic t : topics) {
                System.out.println("DIA ACTUAL: " + fechaActual.getDay());
                System.out.println("DIA DEL TOPICO: " + t.getCreationDate().getDay());
                if (((fechaActual.getDate() - t.getCreationDate().getDate()) < 2) && (fechaActual.getMonth() == t.getCreationDate().getMonth()) && (fechaActual.getYear() == t.getCreationDate().getYear())) {
                    lastTopics.add(t);
                }
            }
            return lastTopics;
        }
        return topics;
    }

    public List<Topic> getTopics() {
        List<Topic> topics = getTotalTopics();
        int index = 50 * getTreeForum();
        List<Topic> topicos = new ArrayList<Topic>();
        int end;
        if (((index + 50)) < (topics.size())) {
            end = index + 50;
        } else {
            end = index + (topics.size() % 50);
        }

        for (int i = index; i < end; i++) {
            topicos.add(topics.get(i));
            topics.get(i).getDepth();

        }
        return topicos;
    }

    public Nick getFindNick() {
        Nick nick = null;
        SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
        for (Nick n : sessionBean.getNicks()) {
            if (nickId.equals(n.getId())) {
                nick = n;
            }
        }
        return nick;
    }

    public String createReply() throws Exception {
        try {
            currentReply.setTopic(getCurrentMessage().getTopic());
            currentReply.setMessage(getCurrentMessage());
            currentReply.setCreationDate(new Date(System.currentTimeMillis()));
            currentReply.setHandle(getFindNick());

            ejbMessages.create(currentReply);
            currentMessage.getMessages().add(currentReply);
            getCurrentMessage().getTopic().getAllMessages().add(currentReply);
            currentReply.getHandle().getMessages().add(currentReply);

            ejbMessages.update(currentMessage);
            ejbTopics.update(getCurrentMessage().getTopic());
            ejbHandles.update(currentReply.getHandle());
            setCreated(true);
            FacesMessage msg = new FacesMessage("Reply created correctly.");
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "success";
        } catch (Exception e) {
            FacesMessage msg = new FacesMessage("Reply already created or user not logged in.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "success";
        }

    }

    public List<Integer> getPages() {
        List<Topic> topics = getTotalTopics();
        List<Integer> pages = new ArrayList<Integer>();
        for (int i = 0; i < (topics.size() / 50) + 1; i++) {
            pages.add(i + 1);
        }
        return pages;
    }

    public String createMessage() throws Exception {
        try {
            currentMessage.setTopic(currentThread);
            currentMessage.setCreationDate(new Date(System.currentTimeMillis()));
            currentMessage.setHandle(getFindNick());
            ejbMessages.create(currentMessage);
            currentMessage.getHandle().getMessages().add(currentMessage);
            currentThread.getAllMessages().add(getCurrentMessage());
            ejbTopics.update(currentThread);
            ejbHandles.update(currentMessage.getHandle());
            setCurrentMessage(null);
            setCreated(true);
            FacesMessage msg = new FacesMessage("Message created correctly.");
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "success";
        } catch (Exception e) {
            FacesMessage msg = new FacesMessage("Message already created or user not logged in.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "success";
        }
    }

    public String createTopic() throws Exception {
        try {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            currentThread.setForum(currentForum);
            currentThread.setHandle(getFindNick());
            currentThread.setCreationDate(new Date(System.currentTimeMillis()));
            ejbTopics.create(currentThread);
            getCurrentForum().getTopics().add(currentThread);
            ejbForums.update(getCurrentForum());
            setCreated(true);
            return "success";
        } catch (Exception e) {
            FacesMessage msg = new FacesMessage("Thread already created or user not logged in.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "success";
        }
    }

    public Boolean follow(Message m, String s) {
        
        if ((m.getSubject().contains(s)) || (m.getContent().contains(s))) {
            System.out.println("ID DEL MENSAJE: " + m.getId());
            getMessagesFound().add(m);
            return true;
        } else {
            for (Message me : m.getMessages()) {
                return follow(me, s);
            }
            return false;
        }
    }
    int i = 0;

    public String searchHandle() {
        handleFound = null;
        String cadena = getHandleSearchString();
        for (Nick h : ejbHandles.listAll()) {
            if (h.getName().matches(cadena)) {
                handleFound = h;
            }
        }
        return "hFound";
    }

    public String search() {
        messagesFound = new ArrayList<Message>();
        String cadena = getSearchString();
        List<Topic> tFound = new ArrayList<Topic>();
        List<Message> mFound = new ArrayList<Message>();

        for (Topic t : currentForum.getTopics()) {
            if (t.getSubject().contains(cadena)) {
                tFound.add(t);
            } else {
                for (Message m : t.getMessages()) {
                        follow(m, cadena);
                }
            }
        }
        threadsFound = tFound;
        System.out.println("Threads econtrados: " + threadsFound.size());
        System.out.println("Mensajes econtrados: " + messagesFound.size());
        return "forumFound";
    }

    public Forum getCurrentForum() {
        return currentForum;
    }

    public void setCurrentForum(Forum currentForum) {
        this.currentForum = currentForum;
    }

    public Topic getCurrentThread() {
        if (currentThread == null) {
            currentThread = new Topic();
        }
        return currentThread;
    }

    public void setCurrentThread(Topic currentThread) {
        this.currentThread = currentThread;
    }

    public int getTreeForum() {
        return treeForum;
    }

    public void setTreeForum(int treeForum) {
        this.treeForum = treeForum;
    }

    public Message getCurrentMessage() {
        if (currentMessage == null) {
            currentMessage = new Message();
        }
        return currentMessage;
    }

    public void setCurrentMessage(Message currentMessage) {
        this.currentMessage = currentMessage;
    }

    public Message getCurrentReply() {
        if (currentReply == null) {
            currentReply = new Message();
        }
        return currentReply;
    }

    public void setCurrentReply(Message currentReply) {
        this.currentReply = currentReply;
    }

    public Long getNickId() {
        return nickId;
    }

    public void setNickId(Long nickId) {
        this.nickId = nickId;
    }

    public Boolean getCreated() {
        return created;
    }

    public void setCreated(Boolean created) {
        this.created = created;
    }

    public Boolean getLast() {
        return last;
    }

    public void setLast(Boolean last) {
        this.last = last;
    }

    public String getHandleSearchString() {
        return handleSearchString;
    }

    public void setHandleSearchString(String handleSearchString) {
        this.handleSearchString = handleSearchString;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public List<Message> getMessagesFound() {
        if (messagesFound == null) {
            messagesFound = new ArrayList<Message>();
        }
        return messagesFound;
    }

    public void setMessagesFound(List<Message> messagesFound) {
        this.messagesFound = messagesFound;
    }

    public List<Topic> getThreadsFound() {
        if (threadsFound == null) {
            threadsFound = new ArrayList<Topic>();
        }
        return threadsFound;
    }

    public void setThreadsFound(List<Topic> threadsFound) {
        this.threadsFound = threadsFound;
    }

    public Nick getHandleFound() {
        return handleFound;
    }

    public void setHandleFound(Nick handleFound) {
        this.handleFound = handleFound;
    }

    public Boolean getPaginate() {
        Boolean reponse = true;
        if ((getTopics().isEmpty()) || (getTotalTopics().size() < 50)) {
            reponse = false;

        }
        return reponse;
    }

    public int getAux1() {
        return aux1;
    }

    public void setAux1(int aux1) {
        this.aux1 = aux1;
    }

    public int getAux2() {
        return aux2;
    }

    public void setAux2(int aux2) {
        this.aux2 = aux2;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }
}
